﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using aspZone.Commerce.DataAccess;
using aspZone.Commerce.Web.App.Models.Catalog;
using aspZone.Commerce.Model;
using aspZone.Commerce.Web.App.Models.Shared;
using System.Web.Caching;

namespace aspZone.Commerce.Web.App.Controllers
{
    public class CatalogController : Controller
    {
        private IProductRepository productRepository;
        protected ICategoryRepository categoryRepository;

        public CatalogController(IProductRepository productRepository, ICategoryRepository categoryRepository)
        {
            this.productRepository = productRepository;
            this.categoryRepository = categoryRepository;
        }

        public ActionResult Index()
        {
            // Add action logic here
            throw new NotImplementedException();
        }

        public ActionResult Product(int id, string name)
        {
            var product = this.productRepository.Get(id);

            if (product == null || product.QuantityAvailable < 1 || !product.Active)
            {
                return View("ProductNotFound");
            }

            ViewData.Model = product;

            return View();
        }

        public ActionResult Category(int id, string name)
        {
            var category = this.categoryRepository.Get(id);

            if (category == null)
            {
                return View("CategoryNotFound");
            }

            var model = new CategoryViewModel();
            model.Category = category;
            model.Products = this.productRepository.FindByCategory(category);
            ViewData.Model = model;
            ViewData["CurrentCategoryId"] = id;

            return View();
        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.Result is ViewResult)
            {
                MasterPageViewDataHelper.AddViewDataRequiredByMasterPage(this.HttpContext.Cache, this.ViewData, this.categoryRepository); ;
            }
        }

        

    }
}
